<template>
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="trTable"
        v-model="searchParams"
        isNeedSelection
        :btnList="btnList"
        :searchShowList="searchShowList"
        :searchHideList="searchHideList"
        :tableData="tableData"
        :tableColumn="tableColumn"
        :total="totalNum"
        requestName="getList"
        @add="operationHandle($event, 'add')"
        @rowEdit="operationHandle($event, 'rowEdit')"
        @rowDelete="operationHandle($event, 'rowDelete')"
        @enabled="operationHandle($event, 'enabled')"
        @unEnabled="operationHandle($event, 'unEnabled')"
        @export="exportHandle"
      />
    </div>
    <TrForm
      v-model="isShowForm"
      title="新增"
      :valueObj.sync="formData"
      :formData="formObj"
      :list="formList"
      :width="480"
      @close="isShowForm = false"
      @confrim="comfrimHandle"
    />
  </div>
</template>
<script>
import { getColor } from "@/utils/billColor";
import {
  getSpotProjectList,
  addProject,
  removeProject,
  updateState,
} from "@/api/accoutrement/spotProject";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrForm from "@/components/Tr-form/Tr-form-popup.vue";
export default {
  name: "SpotProjectBox",
  components: {
    TrTable,
    TrForm,
  },
  data: () => ({
    btnList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      {
        label: "启用",
        option: "enabled",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "停用",
        option: "unEnabled",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "export",
        color: "white",
      },
    ],
    searchShowList: [
      {
        isNeed: true,
        startStr: "createTimeStart",
        endStr: "createTimeEnd",
        id: "creatTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        radio: 1,
        timePeriod: true,
      },
    ],
    searchHideList: [
      {
        id: "code",
        label: "设备点检项编码",
        type: "input",
        value: "",
        width: 33.3,
      },
      {
        id: "checkProperty",
        label: "点检类型",
        type: "multiSelect",
        width: 33.3,
        value: [],
        list: [],
      },
      {
        id: "name",
        label: "设备点检项名称",
        type: "input",
        value: "",
        width: 33.3,
      },
      {
        id: "state",
        label: "状态",
        type: "multiSelect",
        width: 33.3,
        value: [],
        list: [],
      },
    ],
    searchParams: {
      size: 10,
      current: 1,
    },
    totalNum: 0,
    tableColumn: [
      {
        type: "text",
        label: "设备点检项编码",
        value: "code",
        width: 200,
      },
      {
        type: "text",
        label: "状态",
        value: "stateName",
      },
      {
        type: "text",
        label: "设备点检项名称",
        value: "name",
      },
      {
        type: "text",
        label: "点检类型",
        value: "checkPropertyName",
      },
      {
        type: "text",
        label: "计量单位",
        value: "newUtilCode",
      },
      {
        type: "text",
        label: "标准范围",
        value: "newUpper",
      },
      {
        type: "text",
        label: "备注",
        value: "remark",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "修改人员",
        value: "updateUserName",
      },
      {
        type: "text",
        label: "修改时间",
        value: "updateTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "编辑",
            option: "rowEdit",
          },
          {
            label: "删除",
            option: "rowDelete",
          },
        ],
      },
    ],
    tableData: [],
    isShowForm: false,
    formData: {},
    formObj: {},
    formList: [
      {
        label: "设备点检项编码",
        type: "input",
        width: 100,
        value: "",
        placeholder: "系统自动生成",
        id: "code",
        isNeed: false,
        disabled: true,
      },
      {
        label: "设备点检项名称",
        type: "input",
        width: 100,
        value: "",
        id: "name",
      },
      {
        label: "是否启用",
        type: "radio",
        width: 100,
        value: 1,
        list: [
          {
            label: "是",
            value: 1,
          },
          {
            label: "否",
            value: 0,
          },
        ],
        id: "state",
      },
      {
        label: "点检类型",
        type: "radio",
        width: 100,
        value: 20,
        isChange: true,
        list: [
          {
            label: "定性",
            value: 20,
            relaIdsList: [],
          },
          {
            label: "定量",
            value: 10,
            relaIdsList: ["unitCode", "interval"],
          },
        ],
        id: "checkProperty",
      },
      {
        label: "计量单位",
        type: "loadselect",
        width: 100,
        value: "",
        selectedLabel: "",
        reviewLabel: "unitCode(unitName)",
        reviewValue: "u9Code",
        requestObj: {
          url: "/api/trio-system/unit/page",
          method: "post",
          searchKey: "unitName",
          rlLabel: "unitCode(unitName)",
          rlValue: "u9Code",
          resultKey: "data,data,records",
        },
        id: "unitCode",
      },
      {
        label: "标准范围",
        type: "interval",
        width: 100,
        value: [],
        minStr: "lowerValue",
        maxStr: "upperValue",
        id: "interval",
      },

      {
        isNeed: false,
        label: "备注",
        type: "textarea",
        width: 100,
        value: "",
        id: "remark",
      },
    ],
  }),
  computed: {
    ids() {
      return this.$refs.trTable.selectionList.map((item) => item.id);
    },
  },
  methods: {
    exportHandle() {
      this.$exportHandle({ vm: this, params: this.searchParams });
    },
    async initHandle() {
      const res = await this.$fetchEnumApi("mes-equipment-service", [
        "checkPropertyEnum",
        "enabledState",
      ]);
      console.log(res, "resres");
      const proColnum = this.$findByProperty(
        this.searchHideList,
        "id",
        "checkProperty"
      );
      this.$set(proColnum, "list", res["checkPropertyEnum"]);
      const stateColnum = this.$findByProperty(
        this.searchHideList,
        "id",
        "state"
      );
      this.$set(stateColnum, "list", res["enabledState"]);
    },
    resetHandle() {
      this.$message.success(this.$t("msg.success"));
      this.isShowForm = false;
      this.formData = {};
      this.getList();
      this.$refs.trTable.clearSelect();
    },
    comfrimHandle() {
      this.saveHandle(this.formData);
    },
    operationHandle(val, type) {
      this.formObj = type == "rowEdit" ? val : {};
      switch (type) {
        case "add":
          this.isShowForm = true;
          break;
        case "rowEdit":
          val.interval = [val.lowerValue, val.upperValue];
          this.isShowForm = true;
          break;
        case "enabled":
          this.updateStateHandle({
            idList: this.ids,
            state: 1,
          });
          break;
        case "unEnabled":
          this.updateStateHandle({
            idList: this.ids,
            state: 0,
          });
          break;
        case "rowDelete":
          this.removeProjectHandle([val.id], false);
          break;

        default:
          break;
      }
    },
    async getList() {
      const { data: res } = await getSpotProjectList(this.searchParams);
      if (res.code != 200) return this.$message.error(res.msg);
      this.$validateData(res.data.records);
      this.tableData = res.data.records;

      this.tableData.forEach((item) => {
        item["stateNameColor"] = getColor("QT", item.state);
        item["newUtilCode"] = `${item.unitCode}(${item.unitName})`;
        item["newUpper"] = `${item.lowerValue} - ${item.upperValue}`;
      });
      this.totalNum = res.data.total;
    },
    async saveHandle(params) {
      const { data: res } = await addProject(params);
      if (res.code != 200) return;
      this.resetHandle();
    },
    updateStateHandle(params) {
      let tip =
        params.state == 1
          ? this.$t("tip.enableTip")
          : this.$t("tip.unenableTip");
      this.$textShow({
        title: this.$t("tip.label"),
        content: [tip],
      })
        .then(async () => {
          const { data: res } = await updateState(params);
          if (res.code != 200) return;
          this.resetHandle();
        })
        .catch(() => {});
    },
    async removeProjectHandle(idList, forceDel) {
      const { data: res } = await removeProject(idList, forceDel);
      if (res.code != 200) return;
      if (!forceDel) {
        let tip = res.data.haveRelatedPlan
          ? this.$t("tip.deleteStopProject")
          : this.$t("tip.delete");
        this.$textShow({
          title: this.$t("tip.label"),
          content: [tip],
        })
          .then(() => {
            this.removeProjectHandle(idList, true);
          })
          .catch(() => {});
      } else {
        this.resetHandle();
      }
    },
  },
  mounted() {
    this.initHandle();
  },
};
</script>
